package htmodels

import (
	"github.com/astaxie/beego/orm"
	"datapro/models"
)

func HTNodeAdd(node *models.Node) error {
	o := orm.NewOrm()
	_, err := o.Insert(node)
	return err
}

func HTNodeGetDetail(node *models.Node) error {
	o := orm.NewOrm()
	return o.Read(node)
}

func HTNodeGetCount(search string, searchFiled string, Type int, FatherNode int) (int64, error) {
	o := orm.NewOrm()
	m := models.Node{}
	qb := o.QueryTable(m.TableName())
	if Type < 0 {
		qb = qb.Filter(m.FN_Type(), Type)
	}
	if FatherNode < 0 {
		qb = qb.Filter(m.FN_FatherNode(), FatherNode)
	}
	count, err := qb.Filter(searchFiled + "__icontains", search).Count()
	return count, err
}

func HTNodeGetList(nodes *[]models.Node, fields []string, Type int, FatherNode int, offset int64, limit int, search string, searchFiled string, orderby string) error {
	o := orm.NewOrm()
	m := models.Node{}
	qb := o.QueryTable(m.TableName())
	if Type >= 0 {
		qb = qb.Filter(m.FN_Type(), Type)
	}
	if FatherNode >= 0 {
		qb = qb.Filter(m.FN_FatherNode(), FatherNode)
	}
	_, err := qb.Filter(searchFiled + "__icontains", search).OrderBy(orderby).Offset(offset).Limit(limit).All(nodes, fields...)
	return err
}

func HTNodeDelete(Ids []int64) (int64, error) {
	o := orm.NewOrm()
	m := models.Node{}
	count, err := o.QueryTable(m.TableName()).Filter("Id" + "__in", Ids).Delete()
	return count, err
}

func HTNodeUpdate(node *models.Node) error {
	o := orm.NewOrm()
	_, err := o.Update(node)
	return err
}
